package com.rickpan.controller;

import com.rickpan.annotation.RequirePermission;
import com.rickpan.dto.common.ApiResponse;
import com.rickpan.dto.contacts.*;
import com.rickpan.dto.request.CreateFriendGroupRequest;
import com.rickpan.dto.response.FriendGroupResponse;
import com.rickpan.entity.FriendRequest;
import com.rickpan.enums.Permission;
import com.rickpan.service.ContactService;
import com.rickpan.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 联系人管理控制器
 */
@Tag(name = "联系人管理", description = "好友关系、好友申请、用户搜索相关接口")
@RestController
@RequestMapping("/api/contacts")
public class ContactController {

    private static final Logger logger = LoggerFactory.getLogger(ContactController.class);

    @Autowired
    private ContactService contactService;

    // ==================== 好友关系管理 ====================

    @Operation(summary = "获取好友列表", description = "获取当前用户的好友列表，支持分组和关键词筛选")
    @GetMapping
    @RequirePermission(Permission.BASIC_USER)
    public ApiResponse<ContactsListResponse> getFriendsList(
            @Parameter(description = "好友分组") @RequestParam(required = false) String group,
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword) {
        
        Long currentUserId = SecurityUtils.getCurrentUserId();
        logger.info("获取好友列表 userId={}, group={}, keyword={}", currentUserId, group, keyword);
        
        ContactsListResponse response = contactService.getFriendsList(currentUserId, group, keyword);
        return ApiResponse.success(response);
    }

    @Operation(summary = "获取好友列表（分页）", description = "分页获取当前用户的好友列表")
    @GetMapping("/page")
    @RequirePermission(Permission.BASIC_USER)
    public ApiResponse<Page<FriendResponse>> getFriendsPage(
            @Parameter(description = "好友分组") @RequestParam(required = false) String group,
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword,
            @Parameter(description = "页码") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "20") int size) {
        
        Long currentUserId = SecurityUtils.getCurrentUserId();
        logger.info("获取好友列表（分页） userId={}, group={}, keyword={}, page={}, size={}", 
                   currentUserId, group, keyword, page, size);
        
        Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
        Page<FriendResponse> response = contactService.getFriendsPage(currentUserId, group, keyword, pageable);
        return ApiResponse.success(response);
    }



    @Operation(summary = "更新好友信息", description = "更新好友的分组和备注信息")
    @PutMapping("/{relationshipId}")
    @RequirePermission(Permission.BASIC_USER)
    public ApiResponse<FriendResponse> updateFriend(
            @Parameter(description = "好友关系ID") @PathVariable Long relationshipId,
            @Valid @RequestBody UpdateFriendRequest request) {
        
        Long currentUserId = SecurityUtils.getCurrentUserId();
        logger.info("更新好友信息 userId={}, relationshipId={}, request={}", 
                   currentUserId, relationshipId, request);
        
        FriendResponse response = contactService.updateFriend(currentUserId, relationshipId, request);
        return ApiResponse.success(response);
    }

    @Operation(summary = "删除好友", description = "删除好友关系")
    @DeleteMapping("/{relationshipId}")
    @RequirePermission(Permission.BASIC_USER)
    public ApiResponse<Void> deleteFriend(
            @Parameter(description = "好友关系ID") @PathVariable Long relationshipId) {
        
        Long currentUserId = SecurityUtils.getCurrentUserId();
        logger.info("删除好友 userId={}, relationshipId={}", currentUserId, relationshipId);
        
        contactService.deleteFriend(currentUserId, relationshipId);
        return ApiResponse.success();
    }

    @Operation(summary = "获取好友分组", description = "获取当前用户的所有好友分组")
    @GetMapping("/groups")
    @RequirePermission(Permission.BASIC_USER)
    public ApiResponse<List<String>> getFriendGroups() {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        logger.info("获取好友分组 userId={}", currentUserId);

        List<String> groups = contactService.getFriendGroups(currentUserId);
        return ApiResponse.success(groups);
    }

    @Operation(summary = "获取好友分组详细信息", description = "获取当前用户的所有好友分组详细信息")
    @GetMapping("/groups/detail")
    @RequirePermission(Permission.BASIC_USER)
    public ApiResponse<List<FriendGroupResponse>> getFriendGroupsDetail() {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        logger.info("获取好友分组详细信息 userId={}", currentUserId);

        List<FriendGroupResponse> response = contactService.getFriendGroupsDetail(currentUserId);
        return ApiResponse.success(response);
    }

    @Operation(summary = "创建好友分组", description = "创建新的好友分组")
    @PostMapping("/groups")
    @RequirePermission(Permission.BASIC_USER)
    public ApiResponse<FriendGroupResponse> createFriendGroup(@RequestBody CreateFriendGroupRequest request) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        logger.info("创建好友分组 userId={}, groupName={}", currentUserId, request.getGroupName());

        FriendGroupResponse response = contactService.createFriendGroup(currentUserId, request);
        return ApiResponse.success(response);
    }

    @Operation(summary = "删除好友分组", description = "删除指定的好友分组")
    @DeleteMapping("/groups/{groupId}")
    @RequirePermission(Permission.BASIC_USER)
    public ApiResponse<Void> deleteFriendGroup(@PathVariable Long groupId) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        logger.info("删除好友分组 userId={}, groupId={}", currentUserId, groupId);

        contactService.deleteFriendGroup(currentUserId, groupId);
        return ApiResponse.success();
    }

    // ==================== 好友申请管理 ====================

    @Operation(summary = "发送好友申请", description = "向指定用户发送好友申请")
    @PostMapping("/requests")
    @RequirePermission(Permission.BASIC_USER)
    public ApiResponse<FriendRequestResponse> sendFriendRequest(
            @Valid @RequestBody SendFriendRequestRequest request) {
        
        Long currentUserId = SecurityUtils.getCurrentUserId();
        logger.info("发送好友申请 fromUserId={}, toUserId={}", currentUserId, request.getToUserId());
        
        FriendRequestResponse response = contactService.sendFriendRequest(currentUserId, request);
        return ApiResponse.success(response);
    }

    @Operation(summary = "处理好友申请", description = "接受或拒绝好友申请")
    @PutMapping("/requests/{requestId}")
    @RequirePermission(Permission.BASIC_USER)
    public ApiResponse<FriendRequestResponse> handleFriendRequest(
            @Parameter(description = "申请ID") @PathVariable Long requestId,
            @Valid @RequestBody HandleFriendRequestRequest request) {
        
        Long currentUserId = SecurityUtils.getCurrentUserId();
        logger.info("处理好友申请 userId={}, requestId={}, action={}", 
                   currentUserId, requestId, request.getAction());
        
        FriendRequestResponse response = contactService.handleFriendRequest(currentUserId, requestId, request);
        return ApiResponse.success(response);
    }

    @Operation(summary = "获取收到的好友申请", description = "获取当前用户收到的好友申请列表")
    @GetMapping("/requests/received")
    @RequirePermission(Permission.BASIC_USER)
    public ApiResponse<Page<FriendRequestResponse>> getReceivedRequests(
            @Parameter(description = "申请状态") @RequestParam(required = false) FriendRequest.Status status,
            @Parameter(description = "页码") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int size) {
        
        Long currentUserId = SecurityUtils.getCurrentUserId();
        logger.info("获取收到的好友申请 userId={}, status={}, page={}, size={}", 
                   currentUserId, status, page, size);
        
        Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
        Page<FriendRequestResponse> response = contactService.getReceivedRequests(currentUserId, status, pageable);
        return ApiResponse.success(response);
    }

    @Operation(summary = "获取发送的好友申请", description = "获取当前用户发送的好友申请列表")
    @GetMapping("/requests/sent")
    @RequirePermission(Permission.BASIC_USER)
    public ApiResponse<Page<FriendRequestResponse>> getSentRequests(
            @Parameter(description = "申请状态") @RequestParam(required = false) FriendRequest.Status status,
            @Parameter(description = "页码") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int size) {
        
        Long currentUserId = SecurityUtils.getCurrentUserId();
        logger.info("获取发送的好友申请 userId={}, status={}, page={}, size={}", 
                   currentUserId, status, page, size);
        
        Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
        Page<FriendRequestResponse> response = contactService.getSentRequests(currentUserId, status, pageable);
        return ApiResponse.success(response);
    }

    @Operation(summary = "获取待处理申请数量", description = "获取当前用户待处理的好友申请数量")
    @GetMapping("/requests/pending-count")
    @RequirePermission(Permission.BASIC_USER)
    public ApiResponse<Long> getPendingRequestsCount() {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        logger.info("获取待处理申请数量 userId={}", currentUserId);
        
        long count = contactService.getPendingRequestsCount(currentUserId);
        return ApiResponse.success(count);
    }

    // ==================== 用户搜索 ====================

    @Operation(summary = "搜索用户", description = "根据关键词搜索用户")
    @PostMapping("/search")
    @RequirePermission(Permission.BASIC_USER)
    public ApiResponse<Page<UserSearchResponse>> searchUsers(
            @Valid @RequestBody UserSearchRequest request) {

        Long currentUserId = SecurityUtils.getCurrentUserId();
        logger.info("搜索用户 userId={}, keyword={}, searchType={}",
                   currentUserId, request.getKeyword(), request.getSearchType());

        Page<UserSearchResponse> response = contactService.searchUsers(currentUserId, request);
        return ApiResponse.success(response);
    }

    @Operation(summary = "根据用户名查找用户", description = "根据用户名精确查找用户")
    @GetMapping("/search/username/{username}")
    @RequirePermission(Permission.BASIC_USER)
    public ApiResponse<UserSearchResponse> findUserByUsername(
            @Parameter(description = "用户名") @PathVariable String username) {

        Long currentUserId = SecurityUtils.getCurrentUserId();
        logger.info("根据用户名查找用户 userId={}, username={}", currentUserId, username);

        return contactService.findUserByUsername(currentUserId, username)
                .map(ApiResponse::success)
                .orElse(ApiResponse.error("用户不存在或不允许搜索"));
    }

    // ==================== 隐私设置管理 ====================

    @Operation(summary = "获取隐私设置", description = "获取当前用户的隐私设置")
    @GetMapping("/privacy")
    @RequirePermission(Permission.BASIC_USER)
    public ApiResponse<PrivacySettingsResponse> getPrivacySettings() {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        logger.info("获取隐私设置 userId={}", currentUserId);

        PrivacySettingsResponse response = contactService.getPrivacySettings(currentUserId);
        return ApiResponse.success(response);
    }

    @Operation(summary = "更新隐私设置", description = "更新当前用户的隐私设置")
    @PutMapping("/privacy")
    @RequirePermission(Permission.BASIC_USER)
    public ApiResponse<PrivacySettingsResponse> updatePrivacySettings(
            @Valid @RequestBody UpdatePrivacySettingsRequest request) {

        Long currentUserId = SecurityUtils.getCurrentUserId();
        logger.info("更新隐私设置 userId={}, request={}", currentUserId, request);

        PrivacySettingsResponse response = contactService.updatePrivacySettings(currentUserId, request);
        return ApiResponse.success(response);
    }

    // ==================== 统计信息 ====================

    @Operation(summary = "获取联系人统计", description = "获取当前用户的联系人统计信息")
    @GetMapping("/statistics")
    @RequirePermission(Permission.BASIC_USER)
    public ApiResponse<ContactService.ContactsStatistics> getContactsStatistics() {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        logger.info("获取联系人统计 userId={}", currentUserId);

        ContactService.ContactsStatistics statistics = contactService.getFriendsStatistics(currentUserId);
        return ApiResponse.success(statistics);
    }

    // ==================== 管理员功能 ====================

    @Operation(summary = "清理过期申请", description = "清理过期的好友申请（管理员功能）")
    @PostMapping("/admin/cleanup-expired")
    @RequirePermission(Permission.ADMIN)
    public ApiResponse<Integer> cleanupExpiredRequests() {
        logger.info("管理员清理过期申请");

        int cleanedCount = contactService.cleanupExpiredRequests();
        return ApiResponse.success(cleanedCount);
    }
}
